# -*- coding: utf-8 -*-
from odoo import api, fields, models
from odoo.exceptions import ValidationError


class BankBorrowAccountMove(models.Model):
    _inherit = 'account.move'

    borrow_bank_line_id = fields.Many2one(comodel_name='borrow.main.line', string='關聯的還款明細', ondelete='cascade')

class BorrowMain(models.Model):
    _name = 'borrow.main'
    _description = u'銀行借款主檔'

    name = fields.Char(string='借款單號')
    bank_name = fields.Many2one('res.partner', string='借款銀行', required=True)
    interest_rate = fields.Float(string='借款利率', required=True)
    borrow_year = fields.Float(string='借款年期', required=True)
    borrow_principal = fields.Integer(string='借款金額', required=True)
    repayment_principal = fields.Float(string='已還本金', compute='compute_remain')
    remain_principal = fields.Float(string='剩餘本金', compute='compute_remain')
    child_ids = fields.One2many(comodel_name='borrow.main.line', inverse_name='parent_id')
    state = fields.Selection(selection=[(1, u'草稿'), (2, u'借款單'), (3, u'關閉')], string='狀態', default=1)
    account_interest_move = fields.Many2one(string='利息科目', comodel_name='account.account', domain=[('deprecated', '=', False)])
    account_principal_move = fields.Many2one(string='本金科目', comodel_name='account.account', domain=[('deprecated', '=', False)])
    account_bank_move = fields.Many2one(string='銀行存款科目', comodel_name='account.account', domain=[('deprecated', '=', False)])
    borrow_date = fields.Date(string='借款日期', default=fields.Date.context_today)
    count_line = fields.Integer(compute='coumpute_line_ids')

    @api.depends('child_ids')
    def coumpute_line_ids(self):
        for line in self:
            sum = 0
            for row in line.child_ids:
                sum += 1
            line.count_line = sum

    def action_confirm(self):
        self.state = 2

    def close_borrow(self):
        self.state = 3

    @api.onchange('child_ids')
    def compute_remain(self):
        sum = 0
        for line in self.child_ids:
            sum += line.repayment_value
        self.repayment_principal = sum
        self.remain_principal = self.borrow_principal - self.repayment_principal

    # 查看會計憑證用
    def open_move_line(self):
        action = self.env.ref('account.action_move_journal_line').read()[0]
        action['domain'] = [('borrow_bank_line_id', 'in', self.ids)]
        return action


class BorrowMainLine(models.Model):
    _name = 'borrow.main.line'
    _description = u'銀行借款明細檔'

    parent_id = fields.Many2one(comodel_name='borrow.main', string='借款主檔')

    repayment_value = fields.Float(string='還款金額')
    move_id = fields.Many2one(comodel_name='account.move', string='會計憑證')
    state = fields.Selection(selection=[(1, u'草稿'), (2, u'已產生會計憑證'), (3, u'關閉')], string='狀態', default=1)

    # 產生會計憑證用：尋找是其他分錄的名字中，屬於某個公司的分錄
    def compute_journal(self, company):
        jounal_list = self.env['account.journal'].search(
            [('company_id', '=', company.id), ('type', '=', 'general'), ('code', '=', 'MISC')])
        return jounal_list.id

    def create_move(self):
        account = self.env['account.move']
        res = []
        credit = {
            'account_id': self.parent_id.account_interest_move.id,
            'credit': self.interest_value,
            'name': u'借款',
            'partner_id': self.parent_id.bank_name.id
        }
        debit = {
            'account_id': self.parent_id.account_principal_move.id,
            'debit': self.repayment_value,
            'name': u'還款',
            'partner_id': self.parent_id.bank_name.id
        }
        res.append([0, 0, credit])
        res.append([0, 0, debit])

        account_id = account.create({
            'journal_id': self.compute_journal(self.env.user.company_id),
            'borrow_bank_line_id': self.id
        })
        account_id.write({
            'line_ids': res,
        })
        self.move_id = account_id.id
        self.state = 2






